import time, md5
from sourenfe.lib.config import *

def get_real_ip(request):
    ip = False
    if request.META.has_key("HTTP_CLIENT_IP"):
        ip = request.META["HTTP_CLIENT_IP"]
    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
        ips = split(request.META['HTTP_X_FORWARDED_FOR'], ', ')
        if ip:
            ips.insert(0, ip)
            ip = False
        for ip in ips:
            if not (ip.startwith('10.') or ip.startwith('172.16.') or ip.startwith('192.168.')):
                 break
    return (ip if ip else request.META['REMOTE_ADDR'])

def get_cookie_id(request):
    if request.COOKIES.has_key('UID'):
        UID = request.COOKIES['UID']
        return UID, False
    else:
        ip = get_real_ip(request)
        timestamp = time.time()
        UID = md5.md5(ip + str(timestamp)).hexdigest()
        expiretime = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + COOKIE_EXPIRE_PERIOD))
        #response.set_cookie('UID', UID, expiretime)
        return UID, expiretime

def avoid_refresh_dup(response):
    import time
    response['Last-Modified'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
    response['Expires'] = 'Wed, 11 Jan 1984 05:00:00 GMT'
    response['Cache-Control'] = 'no-cache, must-revalidate, max-age=0'
    response['Pragma'] = 'no-cache'
    return response

